<?php

namespace App\Containers\AppSection\Type\Tasks;

use App\Containers\AppSection\Type\Data\Repositories\TypeRepository;
use App\Ship\Exceptions\NotFoundException;
use App\Ship\Parents\Tasks\Task;
use Exception;

class FindTypeByKeyTask extends Task
{
    protected TypeRepository $repository;

    public function __construct(TypeRepository $repository)
    {
        $this->repository = $repository;
    }

    public function run(string $key, string $table = '')
    {
        try {
            $type = empty($table)
                ? $this->repository->findWhere(['key', '=', $key])
                : $this->repository->findWhere([['key', '=', $key], ['table', '=', $table],]);
        } catch (Exception $e) {
            throw new NotFoundException(__('ship::resource.not-found'));
        }

        return $type;
    }
}
